package ex55.mm.flow.impound.quote;

import com.fasterxml.jackson.core.JsonParseException;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.web.HttpMediaTypeException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public HashMap<String, Object> handleException(HttpServletResponse httpServletResponse,
                                                   HttpServletRequest request,
                                                   Exception exception) {
        Throwable e = exception;
        Throwable cause = ExceptionUtils.getRootCause(exception);
        if (cause != null) {
            e = cause;
        }

        HashMap<String, Object> map = new HashMap<>();

        if (e instanceof IllegalArgumentException
                || e instanceof JsonParseException
                || e instanceof ServletRequestBindingException
                || e instanceof HttpRequestMethodNotSupportedException
                || e instanceof HttpMediaTypeException
        ) {
            httpServletResponse.setStatus(400);
            map.put("code", "400");
            map.put("message", e.getMessage());
        } else {
            httpServletResponse.setStatus(500);
            map.put("code", "500");
            map.put("message", e.getMessage());
        }

        exception.printStackTrace();
        return map;
    }
}
